import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Reg from '../views/Reg'
import Login from '../views/Login'
import Search from '../views/home/search.vue'
import Myselfdata from '../views/home/myselfdata.vue'
import Editdata from '../views/home/myselfdata/editdata.vue'
import Play from '../views/play'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/reg',
    name: 'Reg',
    component: Reg
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/search',
    name: 'search',
    component: Search
  },
  {
    path: '/home/myselfdata',
    name: 'myselfdata',
    component: Myselfdata
  },
  {
    path: '/home/myselfdata/editdata',
    name: 'editdata',
    component: Editdata
  },
  {
    path: '/play',
    name: 'play',
    component: Play
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const userInfo = sessionStorage.getItem('token')
  // 获取登录存储的数据
  if (to.path === '/login' || to.path === '/reg' || to.path === '/home' || to.path === '/play' || to.path === '/search') {
    // 如果当前进入页面是登录或注册就不执行任何操作，继续进入。
    next()
  } else {
    // 否则判断是否存在登录存储的数据，不存在就进入登录页面
    if (userInfo === null) {
      next('/home')
    } else {
      next()
    }
  }
})
export default router
